package org.yanghe.config;


import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

public class NacosConfigTest {

    public static void main(String[] args) throws NacosException, InterruptedException {
        encryptPassword();
    }

    /**
     * nacos 登录密码加密生成
     */
    public static void encryptPassword(){
        String content = new BCryptPasswordEncoder().encode("123");
        System.out.println(content);
    }

    /**
     * 获取 nacos 远程配置
     * @throws NacosException
     * @throws InterruptedException
     */
    public static void getNacosConfig() throws NacosException, InterruptedException {
        //Nacos 地址
        String serverAddr = "127.0.0.1:8848";
        //Data Id
        String dataId = "nacos.cfg.dataId";
        //Group
        String group = "test";
        //namespace
        String namespace="11d32e1b-4075-497c-a830-247f03a81f0f";

        Properties properties = new Properties();
        properties.put("serverAddr",serverAddr);
        properties.put("namespace",namespace);//未指定 namespace 时，取 public
        ConfigService configService = NacosFactory.createConfigService(properties);
        //获取配置
        String content = configService.getConfig(dataId,group,5000);
        System.out.println(content);

        //添加监听事件
        configService.addListener(dataId, group, new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String s) {
                System.out.println(s);
            }
        });
        while (true){
            TimeUnit.SECONDS.sleep(2);
        }
    }


}
